package top.yongyan0624.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import top.yongyan0624.common.lang.Result;
import top.yongyan0624.entity.Nanny;
import top.yongyan0624.entity.NannyType;
import top.yongyan0624.utils.OSSUtils;

import java.util.Arrays;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yongyan
 * @since 2021-12-29
 */
@RestController
@RequestMapping("/nanny")
public class NannyController extends BaseController {
    @GetMapping("/list")
    public Result list(String type, String name, String userId) {
        NannyType t = null;
        if (StrUtil.isNotBlank(type)) {
            t = nannyTypeService.getOne(new QueryWrapper<NannyType>().eq("name", type));
        }
        Page<Nanny> pageData = nannyService.page(getPage(), new QueryWrapper<Nanny>()
                .eq(t != null, "type_id", t != null ? t.getId() : null)
                .eq(StrUtil.isNotBlank(userId), "user_id", userId)
                .like(StrUtil.isNotBlank(name), "name", name).orderByDesc("create_time"));

        pageData.getRecords().forEach(n -> {
            n.setUser(sysUserService.getById(n.getUserId()));
            n.setType(nannyTypeService.getOne(new QueryWrapper<NannyType>().eq("id", n.getTypeId())).getName());
        });

        return Result.success(pageData);
    }

    @GetMapping("/info/{id}")
    public Result list(@PathVariable("id") Long id) {
        Nanny nanny = nannyService.getById(id);
        if (nanny == null) {
            return Result.fail("该保姆不存在");
        }

        nanny.setUser(sysUserService.getById(nanny.getUserId()));
        nanny.setType(nannyTypeService.getOne(new QueryWrapper<NannyType>().eq("id", nanny.getTypeId())).getName());

        return Result.success(nanny);
    }

    @PostMapping("/save")
    @PreAuthorize("hasRole('admin')")
    public Result save(@RequestPart Nanny nanny, @RequestPart MultipartFile img) {
        try {
            if (img.isEmpty()) {
                return Result.fail("文件为空");
            }
            //文件不为空，处理文件，存储文件到oss并生成url
            String url = OSSUtils.getImgUrl(img);

            //设置img URL路径
            nanny.setImg(url);

        } catch (IllegalStateException e) {
            e.printStackTrace();
            return Result.fail("图片上传失败");
        }

        NannyType type = nannyTypeService.getOne(new QueryWrapper<NannyType>().eq("name", nanny.getType()));
        if (type == null) {
            return Result.fail("保姆类型名不存在");
        }

        nanny.setTypeId(type.getId());
        //保存nanny
        nannyService.save(nanny);

        nanny.setUser(sysUserService.getById(nanny.getUserId()));

        return Result.success(nanny);
    }


    @PostMapping("/update")
    @PreAuthorize("hasRole('admin')")
    public Result update(@RequestPart Nanny nanny, @RequestPart(required = false) MultipartFile img) {
        if (img != null) {
            try {
                //文件不为空，处理文件，存储文件到oss并生成url
                String url = OSSUtils.getImgUrl(img);
                //设置url
                nanny.setImg(url);
            } catch (IllegalStateException e) {
                e.printStackTrace();
                return Result.fail("图片上传失败");
            }
        }

        if (nanny.getType() != null) {
            NannyType type = nannyTypeService.getOne(new QueryWrapper<NannyType>().eq("name", nanny.getType()));
            if (type == null) {
                return Result.fail("保姆类型名不存在");
            }
            //修改类型ID
            nanny.setTypeId(type.getId());
        }

        //修改保姆信息
        nannyService.updateById(nanny);
        nanny = nannyService.getById(nanny.getId());

        nanny.setUser(sysUserService.getById(nanny.getUserId()));
        nanny.setType(nannyTypeService.getOne(new QueryWrapper<NannyType>().eq("id", nanny.getTypeId())).getName());

        return Result.success(nanny);
    }

    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasRole('admin')")
    public Result delete(@RequestBody Long[] ids) {
        nannyService.removeByIds(Arrays.asList(ids));

        return Result.success("删除成功");
    }
}
